package com.example.common.utils;

import com.example.model.entity.TArea;
import com.example.model.vo.AreaTree;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: zhangr
 * @date: 2018/10/17 13:38
 * @description: 树形工具类
 */
public class TreeUtil {

    /**
     * 数组转树形结构
     * @param organizations
     * @return
     */
    public static List<AreaTree> list2Tree(List<TArea> organizations){
        // 普通对象转树节点
        List<AreaTree> orgTrees = buildTree(organizations);
        List<AreaTree> trees = new ArrayList<>();
        for (AreaTree tree: orgTrees) {
            tree.setLabel(tree.getAreaName());
            if(StringUtils.isBlank(tree.getParentId())) {
                trees.add(tree);
            }
            for (AreaTree t : orgTrees) {
                t.setLabel(t.getAreaName());
                t.setSortNo(t.getSortNo());
                String parentName = "";
                for(TArea area : organizations){
                    if(area.getAreaId().equals(t.getParentId())){
                        parentName = area.getAreaName();
                        break;
                    }
                }
                t.setParentName(parentName);
                if (tree.getAreaId().equals(t.getParentId())) {
                    if (tree.getChildren() == null) {
                        tree.setChildren(new ArrayList<AreaTree>());
                    }
                    tree.addChildren(t);
                }
            }
        }
        return trees;
    }

    /**
     * 对象转树节点
     * @param organizations
     * @return
     */
    public static List<AreaTree> buildTree(List<TArea> organizations){
        List<AreaTree> trees = new ArrayList<>();
        organizations.forEach( resource->{
            AreaTree tree = new AreaTree();
            BeanUtils.copyProperties(resource, tree);
            trees.add(tree);
        });
        return trees;
    }
}
